# -*- coding:utf-8 -*-
# 基础工具
"""
    基础工具，取得DB的配置数据
"""
from functools import wraps
import os
import pkgutil
from threading import local
import warnings

from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.functional import cached_property
from django.utils.importlib import import_module
from django.utils.module_loading import import_by_path
from django.utils._os import upath
from django.utils import six


# 缺省db的标签别名(label alias)
DEFAULT_DB_ALIAS = 'default'


class Error(Exception if six.PY3 else StandardError):
    pass


class InterfaceError(Error):
    pass


class DatabaseError(Error):
    pass


class DataError(DatabaseError):
    pass


class OperationalError(DatabaseError):
    pass


class IntegrityError(DatabaseError):
    pass


class InternalError(DatabaseError):
    pass


class ProgrammingError(DatabaseError):
    pass


class NotSupportedError(DatabaseError):
    pass


# 数据库错误的封装
class DatabaseErrorWrapper(object):
    """
    Context manager and decorator that re-throws backend-specific database
    exceptions using Django's common wrappers.
    内容管理和装饰
    """

    def __init__(self, wrapper):
        """
        wrapper is a database wrapper.

        It must have a Database attribute defining PEP-249 exceptions.
        """
        self.wrapper = wrapper

    def __enter__(self):
        pass

    def __exit__(self, exc_type, exc_value, traceback):
        if exc_type is None:
            return
        for dj_exc_type in (
                DataError,
                OperationalError,
                IntegrityError,
                InternalError,
                ProgrammingError,
                NotSupportedError,
                DatabaseError,
                InterfaceError,
                Error,
            ):
            db_exc_type = getattr(self.wrapper.Database, dj_exc_type.__name__)
            if issubclass(exc_type, db_exc_type):
                # Under Python 2.6, exc_value can still be a string.
                try:
                    args = tuple(exc_value.args)
                except AttributeError:
                    args = (exc_value,)
                dj_exc_value = dj_exc_type(*args)
                dj_exc_value.__cause__ = exc_value
                # Only set the 'errors_occurred' flag for errors that may make
                # the connection unusable.
                if dj_exc_type not in (DataError, IntegrityError):
                    self.wrapper.errors_occurred = True
                six.reraise(dj_exc_type, dj_exc_value, traceback)

    def __call__(self, func):
        # Note that we are intentionally not using @wraps here for performance
        # reasons. Refs #21109.
        def inner(*args, **kwargs):
            with self:
                return func(*args, **kwargs)
        return inner


# 根据指定的后台名，加载后台
# 后台名：backend_name----即后台的类型，比如：'django.db.backends.mysql'，该值是在settings.py中设置的
def load_backend(backend_name):
    # Look for a fully qualified database backend name
    # 查找一个完整、合格的db后台名
    try:
        return import_module('%s.base' % backend_name)              # 加载模块：django.db.backends.mysql.base
    except ImportError as e_user:
        # The database backend wasn't found. Display a helpful error message
        # listing all possible (built-in) database backends.
        backend_dir = os.path.join(os.path.dirname(upath(__file__)), 'backends')
        try:
            builtin_backends = [
                name for _, name, ispkg in pkgutil.iter_modules([backend_dir])
                if ispkg and name != 'dummy']
        except EnvironmentError:
            builtin_backends = []
        if backend_name not in ['django.db.backends.%s' % b for b in
                                builtin_backends]:
            backend_reprs = map(repr, sorted(builtin_backends))
            error_msg = ("%r isn't an available database backend.\n"
                         "Try using 'django.db.backends.XXX', where XXX "
                         "is one of:\n    %s\nError was: %s" %
                         (backend_name, ", ".join(backend_reprs), e_user))
            raise ImproperlyConfigured(error_msg)
        else:
            # If there's some other error, this must be an error in Django
            raise


# 连接不存在的exception
class ConnectionDoesNotExist(Exception):
    pass
# 学习一个技巧：
#    Exception本来是一个通用的报异常的工具，
#    那么可以采用继承的方式，可以针对每一个模块、甚至是类提供一个该异常表示类，比如这里的ConnectionDoesNotExist


# 建立与数据库连接的句柄
class ConnectionHandler(object):
    def __init__(self, databases=None):
        """
        databases is an optional dictionary of database definitions (structured
        like settings.DATABASES).
        """
        self._databases = databases                 # database，表示dict类型的db配置信息
        self._connections = local()                 # from threading import local，线程局部变量的类对象，记录的是连接

    # 初始化_databases数据，并为实例对象生成一个成员databases
    @cached_property
    def databases(self):
        if self._databases is None:
            self._databases = settings.DATABASES            # 加载与mysql建立连接的database参数
        if self._databases == {}:
            self._databases = {
                DEFAULT_DB_ALIAS: {                         # DEFAULT_DB_ALIAS = 'default',setting配置文件中database对应的配置也是default
                    'ENGINE': 'django.db.backends.dummy',
                },
            }
        if DEFAULT_DB_ALIAS not in self._databases:
            raise ImproperlyConfigured("You must define a '%s' database" % DEFAULT_DB_ALIAS)
        return self._databases

    # 确认default配置
    def ensure_defaults(self, alias):
        """
        Puts the defaults into the settings dictionary for a given connection
        where no settings is provided.
        """
        # 获取一个连接，其中涉及各种参数，均来至setting中的DATABASES中的default
        try:
            conn = self.databases[alias]                # 根据别名，取出db的连接，此时该连接为一个dict类型结构
        except KeyError:
            raise ConnectionDoesNotExist("The connection %s doesn't exist" % alias)

        # 向dict中设置各种参数
        conn.setdefault('ATOMIC_REQUESTS', False)
        if settings.TRANSACTIONS_MANAGED:
            warnings.warn(
                "TRANSACTIONS_MANAGED is deprecated. Use AUTOCOMMIT instead.",
                PendingDeprecationWarning, stacklevel=2)
            conn.setdefault('AUTOCOMMIT', False)
        conn.setdefault('AUTOCOMMIT', True)
        conn.setdefault('ENGINE', 'django.db.backends.dummy')
        if conn['ENGINE'] == 'django.db.backends.' or not conn['ENGINE']:
            conn['ENGINE'] = 'django.db.backends.dummy'
        conn.setdefault('CONN_MAX_AGE', 0)
        conn.setdefault('OPTIONS', {})
        conn.setdefault('TIME_ZONE', 'UTC' if settings.USE_TZ else settings.TIME_ZONE)
        for setting in ['NAME', 'USER', 'PASSWORD', 'HOST', 'PORT']:
            conn.setdefault(setting, '')
        for setting in ['TEST_CHARSET', 'TEST_COLLATION', 'TEST_NAME', 'TEST_MIRROR']:
            conn.setdefault(setting, None)

    # ConnectionHandler的实例connections，那么该接口实现的功能为，connections['xxx']
    # 该接口是获取db connection的关键之处，在本人的通常项目中，alias的值为'default'
    def __getitem__(self, alias):
        if hasattr(self._connections, alias):
            return getattr(self._connections, alias)        # 非第一次调用该接口，那么就可以直接getattr()获取结果

        # 1、取出采用的db的dict配置信息
        self.ensure_defaults(alias)                         # 向dict类型的connection中补充参数
        db = self.databases[alias]                          # 取出的db，其为dict类型
        # 2、加载的后台为：django.db.backends.mysql.base
        backend = load_backend(db['ENGINE'])                # 取出engine，表明是那种类型的数据库，加载后台
        # 3、利用db(dict字典类型)和alias('default')创建一个db的封装类
        conn = backend.DatabaseWrapper(db, alias)
        setattr(self._connections, alias, conn)             # 将连接封装到connection实例中的_connections成员，下次就可以直接取用
        return conn                                         # 返回连接，此时连接为DatabaseWrapper类的实例

    def __setitem__(self, key, value):
        setattr(self._connections, key, value)

    def __delitem__(self, key):
        delattr(self._connections, key)

    def __iter__(self):
        return iter(self.databases)

    def all(self):
        return [self[alias] for alias in self]


# 建立与数据连接的路由句柄
class ConnectionRouter(object):
    def __init__(self, routers=None):
        """
        If routers is not specified, will default to settings.DATABASE_ROUTERS.
        如果routers没有指定，那么缺省从settings.DATABASE_ROUTERS中获取内容
        """
        # 这里在初始化时为，router = ConnectionRouter()，创建实例
        self._routers = routers

    @cached_property
    def routers(self):
        if self._routers is None:
            self._routers = settings.DATABASE_ROUTERS
        routers = []                                    # 初始化routers为空的list
        for r in self._routers:
            if isinstance(r, six.string_types):
                router = import_by_path(r)()
            else:
                router = r
            routers.append(router)
        return routers

    # 根据传入的action字符串得到对应的接口(read/write)
    # 该接口的实际调用细节，需要参考《http://my.oschina.net/u/572994/blog/108533》资料来学习较好
    def _router_func(action):
        def _route_db(self, model, **hints):
            chosen_db = None
            for router in self.routers:
                try:
                    method = getattr(router, action)
                except AttributeError:
                    # If the router doesn't have a method, skip to the next one.
                    pass
                else:
                    chosen_db = method(model, **hints)
                    if chosen_db:
                        return chosen_db
            try:
                return hints['instance']._state.db or DEFAULT_DB_ALIAS
            except KeyError:
                return DEFAULT_DB_ALIAS
        return _route_db

    db_for_read = _router_func('db_for_read')           # 获取只读db
    db_for_write = _router_func('db_for_write')         # 获取只写db

    def allow_relation(self, obj1, obj2, **hints):
        for router in self.routers:
            try:
                method = router.allow_relation
            except AttributeError:
                # If the router doesn't have a method, skip to the next one.
                pass
            else:
                allow = method(obj1, obj2, **hints)
                if allow is not None:
                    return allow
        return obj1._state.db == obj2._state.db

    def allow_syncdb(self, db, model):
        for router in self.routers:
            try:
                method = router.allow_syncdb
            except AttributeError:
                # If the router doesn't have a method, skip to the next one.
                pass
            else:
                allow = method(db, model)
                if allow is not None:
                    return allow
        return True
